//
// Created by zzc on 17-12-26.
// 预计完成时间: 18-1-10
//

#include "sds.h"
#include "zmalloc.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

sds sdsnewlen(const void *init, size_t initlen)
{
    struct sdshdr *s ;
    if(init) {
        s = zmalloc(sizeof(*s) + initlen + 1);
    } else {
        s = zcalloc(sizeof(*s) + initlen + 1);
    }

    if(NULL == s) {
        return NULL;
    }

    s->len = initlen;
    s->free = 0;

    if(initlen && init) {
        memcpy(s->buf, init, initlen);
    }

    s->buf[initlen] = '\0';

    return (sds)s->buf;

}
sds sdsempty(void)
{
    return sdsnewlen(NULL, 0);
}
sds sdsnew(const char *init)
{
    if(init) {
        return sdsnewlen(init, strlen(init));
    } else {
        return sdsempty();
    }
}

sds sdsdup(const sds s)
{
    return sdsnewlen(s, sdslen(s));
}


void sdsfree(sds s)
{
    if(NULL == s)
        return ;
    zfree(s - sizeof(struct sdshdr));
}

size_t sdslen(const sds s)
{
    struct sdshdr *p = (struct sdshdr *)(s - sizeof(struct sdshdr));
    return p->len;
}
size_t sdsavail(const sds s)
{
    struct sdshdr *p = (struct sdshdr *)(s - sizeof(struct sdshdr));
    return p->free;
}

sds sdsgrowzero(sds s, size_t len)
{
    size_t now_len = sdslen(s);
    struct sdshdr *p;
    if(now_len >= len)
        return s;

    s = sdsMakeRoomFor(s, len - now_len);
    if(s == NULL)
        return NULL;

    memset(s + now_len, 0, len - now_len + 1);
    p = (struct sdshdr *)(s - sizeof(struct sdshdr));
    p->len = len;
    p->free = p->free + now_len - p->len;
    return s;

}

sds sdscatlen(sds s, const void *t, size_t len)
{
    if(t == NULL || len <= 0)
        return s;
    size_t  now_len = sdslen(s);
    s = sdsMakeRoomFor(s, len);
    if(s == NULL)
        return s;
    memcpy(s + now_len, t, len);
    s[now_len + len] = '\0';
    struct sdshdr *p = (struct sdshdr *)(s - sizeof(struct sdshdr));
    p->len = now_len + len;
    p->free = p->free - len;
    return s;

}

sds sdscat(sds s, const char *t)
{
    if(t == NULL)
        return s;
    return sdscatlen(s, t, strlen(t));
}

sds sdscatsds(sds s, const sds t)
{
    if(t == NULL)
        return s;
    return sdscatlen(s, t, sdslen(t));
}



sds sdsMakeRoomFor(sds s, size_t addlen)
{
    struct sdshdr *now_p, *new_p;
    size_t now_free = sdsavail(s);
    size_t new_len;
    size_t len;

    if(now_free >= addlen)
        return s;

    now_p = (struct sdshdr *)(s - sizeof(struct sdshdr));

    len = sdslen(s);
    new_len = len + addlen;

    if(new_len < SDS_MAX_PREALLOC) {
        new_len *= 2;
    } else {
        new_len += SDS_MAX_PREALLOC;
    }

    new_p = zrealloc(now_p, sizeof(struct sdshdr) + new_len + 1);

    if(new_p == NULL)
        return NULL;

    new_p->free = new_len - len;

    return new_p->buf;
}

sds sdscpylen(sds s, const char *t, size_t len)
{
    if(t == NULL)
        return s;
    struct sdshdr  *p = (struct sdshdr *)(s - sizeof(struct sdshdr));
    if(p->free + p->len < len) {
        s = sdsMakeRoomFor(s, len - p->len);
        if(s == NULL)
            return s;
        p = (struct sdshdr *)(s - sizeof(struct sdshdr));
    }
    memcpy(s, t, len);
    s[len] = '\0';
    p->free = p->free + p->len -  len;
    p->len = len;
    return s;

}

sds sdscpy(sds s, const char *t)
{
    if(t == NULL)
        return s;
    return sdscpylen(s, t, strlen(t));
}

sds sdstrim(sds s, const char *cset)
{
    struct sdshdr  *p = (struct sdshdr *)(s - sizeof(struct sdshdr));

    char *begin, *end, *sp, *ep;

    size_t  len;

    begin = sp = p->buf;

    end = ep = p->buf + p->len - 1;

    while(sp <= end && strchr(cset, *sp)) sp++;
    while(ep >= begin && strchr(cset, *ep)) ep--;

    len = (ep > sp) ? ep - sp + 1 : 0;

    if(p->buf != sp) memmove(p->buf, sp, len);

    p->buf[len] = '\0';

    p->free = p->free + p->len - len;
    p->len = len;

    return s;

}

sds sdscatvprintf(sds s, const char *fmt, va_list ap)
{
    va_list cpy;
    char staticbuf[1024], *buf = staticbuf, *t;
    size_t buflen = strlen(fmt)*2;

    /* We try to start using a static buffer for speed.
     * If not possible we revert to heap allocation. */
    if (buflen > sizeof(staticbuf)) {
        buf = zmalloc(buflen);
        if (buf == NULL) return NULL;
    } else {
        buflen = sizeof(staticbuf);
    }

    /* Try with buffers two times bigger every time we fail to
     * fit the string in the current buffer size. */
    while(1) {
        buf[buflen-2] = '\0';
        va_copy(cpy,ap);
        // T = O(N)
        vsnprintf(buf, buflen, fmt, cpy);
        if (buf[buflen-2] != '\0') {
            if (buf != staticbuf) zfree(buf);
            buflen *= 2;
            buf = zmalloc(buflen);
            if (buf == NULL) return NULL;
            continue;
        }
        break;
    }

    /* Finally concat the obtained string to the SDS string and return it. */
    t = sdscat(s, buf);
    if (buf != staticbuf) zfree(buf);
    return t;
}

sds sdscatprintf(sds s, const char *fmt, ...) {
    va_list ap;
    char *t;
    va_start(ap, fmt);
    // T = O(N^2)
    t = sdscatvprintf(s,fmt,ap);
    va_end(ap);
    return t;
}
#define SDS_LLSTR_SIZE 21
int sdsll2str(char *s, long long value) {
    char *p, aux;
    unsigned long long v;
    size_t l;

    /* Generate the string representation, this method produces
     * an reversed string. */
    v = (value < 0) ? -value : value;
    p = s;
    do {
        *p++ = '0'+(v%10);
        v /= 10;
    } while(v);
    if (value < 0) *p++ = '-';

    /* Compute length and add null term. */
    l = p-s;
    *p = '\0';

    /* Reverse the string. */
    p--;
    while(s < p) {
        aux = *s;
        *s = *p;
        *p = aux;
        s++;
        p--;
    }
    return l;
}

int sdsull2str(char *s, unsigned long long v) {
    char *p, aux;
    size_t l;

    /* Generate the string representation, this method produces
     * an reversed string. */
    p = s;
    do {
        *p++ = '0'+(v%10);
        v /= 10;
    } while(v);

    /* Compute length and add null term. */
    l = p-s;
    *p = '\0';

    /* Reverse the string. */
    p--;
    while(s < p) {
        aux = *s;
        *s = *p;
        *p = aux;
        s++;
        p--;
    }
    return l;
}

sds sdscatfmt(sds s, char const *fmt, ...) {
    struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
    size_t initlen = sdslen(s);
    const char *f = fmt;
    int i;
    va_list ap;

    va_start(ap,fmt);
    f = fmt;    /* Next format specifier byte to process. */
    i = initlen; /* Position of the next byte to write to dest str. */
    while(*f) {
        char next, *str;
        size_t l;
        long long num;
        unsigned long long unum;

        /* Make sure there is always space for at least 1 char. */
        if (sh->free == 0) {
            s = sdsMakeRoomFor(s,1);
            sh = (void*) (s-(sizeof(struct sdshdr)));
        }

        switch(*f) {
            case '%':
                next = *(f+1);
                f++;
                switch(next) {
                    case 's':
                    case 'S':
                        str = va_arg(ap,char*);
                        l = (next == 's') ? strlen(str) : sdslen(str);
                        if (sh->free < l) {
                            s = sdsMakeRoomFor(s,l);
                            sh = (void*) (s-(sizeof(struct sdshdr)));
                        }
                        memcpy(s+i,str,l);
                        sh->len += l;
                        sh->free -= l;
                        i += l;
                        break;
                    case 'i':
                    case 'I':
                        if (next == 'i')
                            num = va_arg(ap,int);
                        else
                            num = va_arg(ap,long long);
                        {
                            char buf[SDS_LLSTR_SIZE];
                            l = sdsll2str(buf,num);
                            if (sh->free < l) {
                                s = sdsMakeRoomFor(s,l);
                                sh = (void*) (s-(sizeof(struct sdshdr)));
                            }
                            memcpy(s+i,buf,l);
                            sh->len += l;
                            sh->free -= l;
                            i += l;
                        }
                        break;
                    case 'u':
                    case 'U':
                        if (next == 'u')
                            unum = va_arg(ap,unsigned int);
                        else
                            unum = va_arg(ap,unsigned long long);
                        {
                            char buf[SDS_LLSTR_SIZE];
                            l = sdsull2str(buf,unum);
                            if (sh->free < l) {
                                s = sdsMakeRoomFor(s,l);
                                sh = (void*) (s-(sizeof(struct sdshdr)));
                            }
                            memcpy(s+i,buf,l);
                            sh->len += l;
                            sh->free -= l;
                            i += l;
                        }
                        break;
                    default: /* Handle %% and generally %<unknown>. */
                        s[i++] = next;
                        sh->len += 1;
                        sh->free -= 1;
                        break;
                }
                break;
            default:
                s[i++] = *f;
                sh->len += 1;
                sh->free -= 1;
                break;
        }
        f++;
    }
    va_end(ap);

    /* Add null-term */
    s[i] = '\0';
    return s;
}

void sdsrange(sds s, int start, int end)
{
    struct sdshdr *sh = (struct sdshdr *)(s - sizeof(struct sdshdr));

    size_t origin_len = sdslen(s);
    size_t origin_free = sdsavail(s);
    int new_len;
    if(origin_len == 0)
        return ;
    if(start < 0) {
        start = origin_len + start;
        if(start < 0)
            start = 0;
    }

    if(end < 0) {
        end = origin_len + end;
        if(end < 0)
            end = 0;
    }

    if(end - start < 0) {
        new_len = 0;
    }else
        new_len = end - start + 1;

    if(new_len != 0) {
        if(start >= (signed)origin_len) {
            new_len = 0;
        } else if(end >= (signed)origin_len) {
            end = origin_len - 1;
            new_len = (start > end) ? 0 : (end - start) + 1;
        }
    } else {
        start = 0;
    }

    if(start && new_len)
        memmove(s, s + start, new_len);
    s[new_len] = '\0';
    sh->len = new_len;
    sh->free = origin_len + origin_free - new_len;
}
void sdsclear(sds s)
{
    struct sdshdr *sh = (struct sdshdr *)(s - sizeof(struct sdshdr));

    sh->free = sh->free + sh->len;
    sh->len = 0;
    s[0] = '\0';
}
int sdscmp(const sds s1, const sds s2)
{
    size_t l1 = sdslen(s1);
    size_t l2 = sdslen(s2);
    size_t min_len = l1 > l2 ? l2 : l1;

    int cmp = memcmp(s1, s2, min_len);
    if(cmp == 0)
        return l1 - l2;
    return cmp;
}

sds *sdssplitlen(const char *s, int len, const char *sep, int seplen, int *count)
{
    int elements = 0, slots = 5, start = 0, j;
    sds *tokens;

    if(len < 0 || seplen < 1)
        return NULL;
    tokens = zmalloc(sizeof(sds *) * slots);
    if(tokens == NULL)
        goto cleanup;


    if(len == 0) {
        *count = 0;
        return tokens;
    }

    for(j = 0; j < (len - seplen + 1); j++) {
        if(slots < elements + 2) {
            slots *= 2;
            tokens = zrealloc(tokens, sizeof(sds *) * slots);
            if(tokens == NULL) goto cleanup;
        }
        if( (seplen == 1 && sep[0] == s[j]) || memcmp(s + j, sep, seplen) == 0) {
            tokens[elements] = sdsnewlen(s + start, j - start);
            if(tokens[elements] == NULL) goto cleanup;
            elements++;
            start = j + seplen;
            j = j + seplen - 1;
        }
    }

    tokens[elements] = sdsnewlen(s + start, len - start);
    if(tokens[elements] == NULL) goto cleanup;
    elements++;
    *count = elements;
    return tokens;


cleanup:
    {
        for(int i = 0; i < elements; i++)
            zfree(tokens[i]);
        *count = 0;
        return NULL;
    }
}

void sdsfreesplitres(sds *tokens, int count)
{
    if(!tokens)
        return;
    for(int i = 0; i < count; i++) {
        sdsfree(tokens[i]);
    }
    zfree(tokens);
}

void sdstolower(sds s)
{
    size_t len = sdslen(s);
    for(size_t i = 0; i < len; i++) {
        s[i] = tolower(s[i]);
    }
}

void sdstoupper(sds s)
{
    size_t len = sdslen(s);
    for(size_t i = 0; i < len; i++) {
        s[i] = toupper(s[i]);
    }
}

sds sdsfromlonglong(long long value)
{
    char buf[SDS_LLSTR_SIZE];
    int len = sdsll2str(buf,value);

    return sdsnewlen(buf,len);
}
sds sdsjoin(char **argv, int argc, char *sep)
{
    sds r = sdsempty();

    for(int i = 0; i < argc; i++) {
        if(i != 0) {
            r = sdscat(r, sep);
        }
        r = sdscat(r, argv[i]);
    }

    return r;

}
